<?php
include_once '../framework/BasePage.page.php';

class EntityGenerator extends BasePage {

    public $DbHtml = "";
    public $TablesHtml = "";
    private $SelectedDatabase;
    private $SelectedTable = "";
    private $EntityRows;
    private $EntityFKRestraints;
    private $DbLink;

    public function Page_Load() {

        $this->getAllDBs();
    }

    private function getAllDBs() {
        $this->DbHtml = "";
        $this->grid = new Grid();
        $this->grid->ExecuteSQL("SHOW DATABASES");

        $this->DbHtml.= "<option value=0 >-- Select --</option>";
        while ($row = $this->grid->FetchNext()) {
            $this->DbHtml.= "<option>" . $row["Database"] . "</option>";
        }
        
        $this->ddlDatabases->html = $this->DbHtml;
    }

    public function getAllTablesForDB() {
        $this->TablesHtml = "";

        $this->grid = new Grid();
        $this->SelectedDatabase = $this->ddlDatabases->val;
        $this->grid->ExecuteSQL("SHOW TABLES FROM $this->SelectedDatabase");

        $this->TablesHtml .= "<option value=0>-- Select --</option>";
        while ($row = $this->grid->FetchNext()) {
            $this->TablesHtml .= "<option>" . $row["Tables_in_$this->SelectedDatabase"] . "</option>";
        }
        $this->ddlTables->html = $this->TablesHtml;
    }

    public function getAllColumnsFromTable() {

        $this->SelectedTable = $this->ddlTables->val;
        $this->grid = new Grid();
        $this->grid->SetDBName($this->SelectedDatabase);

        $this->grid->ExecuteSQL("SHOW COLUMNS FROM $this->SelectedTable");
        $this->EntityRows = $this->grid->FetchAll();
        $this->columns->html = $this->ArrayToTable($this->EntityRows);
        
        $this->EntityFKRestraints = $this->getAllFKRestraints($this->SelectedTable);
    }
    private function getAllFKRestraints($tableName)
    {
       $sql="SELECT i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME 
        FROM information_schema.TABLE_CONSTRAINTS i 
        LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME 
        WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' 
        AND i.TABLE_SCHEMA = DATABASE()
        AND i.TABLE_NAME = '$tableName'";
       $grid = new Grid();
       $grid->ExecuteSQL($sql);
       return $grid->FetchAll();
    }
    public function generateEntity() {
        
        if ($this->SelectedTable != "") {
            $fp = fopen("../generated/genEntity/".ucfirst($this->SelectedTable).".class.php","w");
            $content="<?php
include_once('../Framework/Base.entity.php');

/*******
This File is generated
********/

class ".ucfirst($this->SelectedTable)." extends Base{
                    ";
            foreach ($this->EntityRows as $row) 
            {
             $content.="
    public \$".$row["Field"].";";
               
            }
            $content.="
                
    function __construct()
    {

    }
    
    public function escape(\$grid)
    {";
         foreach ($this->EntityRows as $row) 
         {
            if(strpos($row["Type"],"varchar") !==FALSE || strpos($row["Type"],"text") !== FALSE)
            {
                $content.="
        \$this->".$row["Field"]." = \$grid->Escape(\$this->".$row["Field"].");";
            }
         }
    $content.="
    }
    
    public function validate()
    {";
         foreach ($this->EntityRows as $row) 
         {
            if($row["Null"] == "NO" && $row["Key"] != "PRI")
            {
                $content.="
         if(\$this->".$row["Field"]." == \"\") // Generated
         {
            \$this->AddError(\"".$row["Field"]." is required.\");
         }";
        
       
            }
         }
         if(count($this->EntityFKRestraints) > 0)
         {
             foreach($this->EntityFKRestraints as $row)
             {
                 $referencedTable = $row["REFERENCED_TABLE_NAME"];
                 $referencedColumn = $row["REFERENCED_COLUMN_NAME"];
                 $content.="
         if(\$this->ValidForeignKey(\"$referencedTable\",\$this->$referencedColumn) == false) // Generated
         {
            \$this->AddError(\"Invalid $referencedTable selected.\");
         }";
             }
         }
    $content.="
        //ADDITIONAL VALIDATION RULES GO BELOW HERE
    }
}
?>";
            fwrite($fp, $content);
            fclose($fp);
            $this->columns->html = "File is generated";
        }
        else{
            $this->columns->html = "No Table Selected";
        }
    }

}

?>